<?php

namespace App\HttpController\Applet;

use App\HttpController\BaseController;
use App\Model\VideosModel;

class VideoController extends BaseController {

    public function index(){
        $request= $this->request();
        $chanel = trim($request->getRequestParam('chanel_id')) ?: 0;
        $page   = trim($request->getRequestParam('page')) ?: 1;
        $option = trim($request->getRequestParam('option')) ?: 1;
        $model = new VideosModel();
        $lists = $model->select('id,title,thumb')
            ->where(function($query) use($chanel,$option){
                if ($chanel){
                    $query->where('chanel_id',$chanel);
                }else{
                    $query->where('rand_cate', rand(1, 10));
                }
                if ($option){
                    $query->where('`option`',$option);
                }
            })
            ->orderBy('created_at')
            ->paginate($page,8);
        return $this->writeJson(0,$lists);
    }


    public function info(){
        $request= $this->request();
        $id = $request->getRequestParam('id');
        $openid = trim($request->getRequestParam('openid')) ?: '';
        $shareuid = $request->getRequestParam('shareuid') ?: 0;
        $model = new VideosModel();
        $info = $model->select('id,title,thumb,link')
            ->find($id);
        if(!$info){
            return $this->writeJson(1,null,'数据信息不存在');
        }
        //匹配腾讯视频的vid
        preg_match_all('/\/([0-9a-zA-Z]+).html/', $info['link'], $matchs);
        $vid = $matchs[1][0] ?: '';
        $info['vid'] = $vid;
        // TODO::增加总人气记录
        // TODO::增加统计记录
        return $this->writeJson(0,$info);
    }



    public function randList(){
        $request= $this->request();
        $id = $request->getRequestParam('id');
        if (empty($id)) {
            return $this->writeJson(1, null,'参数错误');
        }
        $model = new VideosModel();
        $lists = $model->select('id,title,thumb')
            ->where('id', $id, '<>')
            ->take(20)
            ->inRandomOrder()
            ->get();
        return $this->writeJson(0, $lists);
    }


    public function getBanner(){
        $model = new VideosModel();
        $lists = $model->select('id,title,thumb')
            ->where('banner', 2)
            ->get();
        return $this->writeJson(0, $lists);
    }

}
